import 'package:flutter/material.dart';
import 'package:jd_flutter/base/widget/basic/jd_state.dart';

import '../../pre_init/pre_init.dart';

abstract class BaseLifecycleState<T extends StatefulWidget> extends JDState<T>
    with RouteAware, WidgetsBindingObserver {
  bool get isTabPage => false;

  bool _isFocusTab = false;
  bool _isFocusWidget = false;

  bool get isFocusWidget => _isFocusWidget;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    kRouteObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (!_isFocusWidget) return;
    if (state == AppLifecycleState.resumed) {
      // 显示
      _onResumed();
    } else if (state == AppLifecycleState.paused) {
      // 离开
      _onPaused();
    }
  }

  void didTabPush() {
    _isFocusTab = true;
    _isFocusWidget = true;
    _onResumed();
  }

  void didTabPop() {
    _isFocusTab = false;
    _isFocusWidget = false;
    _onPaused();
  }

  @override
  void didPush() {
    // tab托管
    if (isTabPage && !_isFocusTab) return;
    // 当前页面进入
    _isFocusWidget = true;
    _onResumed();
  }

  @override
  void didPop() {
    // tab托管
    if (isTabPage && !_isFocusTab) return;
    // 弹出当前页面
    _isFocusWidget = false;
    _onPaused();
  }

  @override
  void didPopNext() {
    // tab托管
    if (isTabPage && !_isFocusTab) return;
    // 下一个页面弹出,自己显示
    _isFocusWidget = true;
    _onResumed();
  }

  @override
  void didPushNext() {
    // tab托管
    if (isTabPage && !_isFocusTab) return;
    // 下一个页面覆盖,自己隐藏
    _isFocusWidget = false;
    _onPaused();
  }

  bool showing = true;

  // 显示
  void _onResumed() {
    onResumed();
    showing = true;
  }

  // 离开
  void _onPaused() {
    onPaused();
    showing = false;
  }

  // 显示
  void onResumed() {}

  // 离开
  void onPaused() {}

  @override
  void dispose() {
    kRouteObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context);
}
